using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

public class Slot
{
    public Vector3Int Position;

    // Direction -> Module -> Number of items in this.getneighbor(direction).Modules that allow this module as a neighbor
    //public short[][] ModuleHealth;

    private AbstractMap map;

    public Module Module;

    public GameObject GameObject;

    public bool Collapsed = false;

    public bool ConstructionComplete
    {
        get
        {
            return this.GameObject != null || !this.Collapsed;
        }
    }

    public Slot(Vector3Int position, AbstractMap map)
    {
        this.Position = position;
        this.map = map;
        //this.ModuleHealth = map.CopyInititalModuleHealth();
    }

    public Slot(Vector3Int position, AbstractMap map, Slot prototype)
    {
        this.Position = position;
        this.map = map;
        //this.ModuleHealth = prototype.ModuleHealth.Select(a => a.ToArray()).ToArray();
    }

    // TODO only look up once and then cache???
    public Slot GetNeighbor(int direction)
    {
        return this.map.GetSlot(this.Position + Orientations.Direction[direction]);
    }

    public void Collapse()
    {
        if (this.Collapsed)
        {
            Debug.LogWarning("Trying to collapse already collapsed slot.");
            return;
        }

        this.map.NotifySlotCollapsed(this);
    }

    private void checkConsistency(Module module)
    {
        for (int d = 0; d < 6; d++)
        {
            if (this.GetNeighbor(d) != null && this.GetNeighbor(d).Collapsed)
            {
                throw new Exception("Illegal collapse, not in neighbour list. (Incompatible connectors)");
            }
        }
    }

    public void CollapseRandom()
    {
        if (this.Collapsed)
        {
            throw new Exception("Slot is already collapsed.");
        }

        this.Collapse();
    }

    // This modifies the supplied ModuleSet as a side effect
    public void RemoveModules(bool recursive = true)
    {
        for (int d = 0; d < 6; d++)
        {
            int inverseDirection = (d + 3) % 6;
            var neighbor = this.GetNeighbor(d);
            if (neighbor == null)
            {
            }
        }

        if (recursive)
        {
            this.map.FinishRemovalQueue();
        }
    }

    public override int GetHashCode()
    {
        return this.Position.GetHashCode();
    }
}
